<template>
  <div>
    <el-card style="margin: 20px 0px">
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTable"></CategorySelect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!Id3"
          @click="addAttr"
          >添加属性</el-button
        >
        <!-- 表格：展示平台属性 -->
        <el-table style="width: 100%" border :data="attrList">
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150"
          ></el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin: 10px"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性或修改属性的结构 -->
      <div v-show="!isShowTable">
        <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>

        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrInfo.attrName"
          >添加属性值</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>

        <el-table
          border
          style="width: 100%; margin: 20px 0px"
          :data="attrInfo.attrValueList"
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                placeholder="请输入属性值名称"
                v-model="row.valueName"
                size="mini"
                v-if="row.flag"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                :ref="$index"
              ></el-input>
              <span
                v-else
                @click="toEdit(row, $index)"
                style="dispaly: block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row,$index}">
              <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="deleteAttrValue($index)">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr" :disabled="attrInfo.attrValueList.length<1"
          >保存</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash中的深拷贝
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      Id1: "",
      Id2: "",
      Id3: "",
      attrList: [], //存储平台属性的数据
      isShowTable: true, //控制table表格的显示和隐藏
      attrInfo: {
        // 收集新增或修改的属性名
        attrName: "", //属性名
        attrValueList: [
          /* {
            attrId: 0,
            valueName: "",
          }, */
        ],
        categoryId: 0, //三级分类的id
        categoryLevel: 3,
      },
    };
  },
  methods: {
    // 自定义事件的回调
    getCategoryId({ categoryId, level }) {
      console.log(categoryId, level, "attr id和level");
      if (level == 1) {
        this.Id1 = categoryId;
        this.Id2 = "";
        this.Id3 = "";
      } else if (level == 2) {
        this.Id2 = categoryId;
        this.Id3 = "";
      } else {
        // 代表三级分类的id有了，可以发送请求获取品牌属性
        this.Id3 = categoryId;
        this.getAttrList();
      }
    },
    async getAttrList() {
      // 获取分类的id
      const { Id1, Id2, Id3 } = this;
      let result = await this.$API.attr.reqAttrList(Id1, Id2, Id3);
      console.log(result, "平台属性数据");
      if (result.code == 200) {
        this.attrList = result.data;
      }
    },
    // 添加属性值按钮的回调
    addAttrValue() {
      // 向属性值数组里添加元素
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: "",
        flag: true, //用于切换属性值的编辑和查看模式
      });
      // 新增属性值自动获取焦点
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus();
      });
    },
    // 添加属性按钮的回调
    addAttr() {
      this.isShowTable = false;
      // 清除收集新增或修改的属性名和属性值
      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.Id3,
        categoryLevel: 3,
      };
    },
    // 修改属性按钮的回调
    updateAttr(row) {
      this.isShowTable = false;
      // console.log(row);
      // 由于数组结构里面存在对象套数组，数组又套对象，因此需要使用深拷贝解决
      this.attrInfo = cloneDeep(row);
      // Vue无法探测普通的新增属性，使用$set添加一个响应式属性
      this.attrInfo.attrValueList.forEach((item) => {
        // item.flag=false;(非响应式)
        this.$set(item, "flag", false);
      });
    },
    // 失去焦点切换为查看模式，展示span
    toLook(row) {
      // 如果属性值为空则不能作为新的属性值，需要给用户提示信息
      if (row.valueName.trim() == "") {
        this.$message("请你输入一个正常的属性值");
        return;
      }
      // 新增的属性值不能与已有的属性值重复
      let isRepeat = this.attrInfo.attrValueList.some((item) => {
        // row是数组的最新一项元素，判断时需要将row去除，不能自己跟自己比较
        if (row !== item) {
          return row.valueName == item.valueName;
        }
      });
      if (isRepeat) {
        this.$message("当前属性值已存在");
        return;
      }
      row.flag = false;
    },
    // 点击span展示input的回调
    toEdit(row, index) {
      row.flag = true;
      // 点击span时，对于浏览器而言，页面重绘一个input是需要耗费时间的，
      // 因此不可能一点击span就立马获取到input
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // 气泡确认框确定按钮的回调
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index,1);
    },
    // 保存按钮的回调
    async addOrUpdateAttr() {
      // 整理参数:空串不应提交，且不应该出现flag字段
      // filter方法返回一个新的数组
      this.attrInfo.attrValueList=this.attrInfo.attrValueList.filter(item => {
        if(item.valueName!='') {
          delete item.flag;
          return true;
        }
      })
      try {
        // 发请求
        await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo);
        this.isShowTable=true;
        this.$message({
          type:'success',
          message:'保存成功'
        });
        this.getAttrList();
      } catch (error) {
        this.$message('保存失败');
      }
    }
  },
};
</script>

<style>
</style>